package com.auth;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.StrutsStatics;

import com.electric.util.CookieUtil;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @author Kevin Zhang
 *
 * 2011-5-10
 */
public class AuthorizationInterceptor extends AbstractInterceptor {
	
	private static final Logger logger = Logger.getLogger(AuthorizationInterceptor.class);
	
	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext actionContext = invocation.getInvocationContext();  
		HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);  
		Map session = invocation.getInvocationContext().getSession();
		//session
		String userName = (String) session.get("userName");
		//cookie
		Cookie[] cookies = request.getCookies();
		String cookieName = cookies == null ? "":CookieUtil.getCookieValue(cookies, "userName");
		
		if (null != userName && userName.equals(cookieName)) {
			logger.warn("拦截器：合法用户登录---");
			return invocation.invoke();
		} else {
			logger.warn("拦截器：用户未登录---");
			return Action.LOGIN;
		}
	}
}
